package de.tempel.pong.util;

import java.awt.geom.Point2D;

public class Line2D extends java.awt.geom.Line2D.Double {

	private static final long serialVersionUID = 1L;
	private final double m;
	private final double n;

	public Line2D(Point2D p1, Point2D p2) {
		super(p1, p2);

		m = (p1.getY() - p2.getY()) / (p1.getX() - p2.getX());

		// y = mx + n
		// n = y - mx
		n = p1.getY() - m * p1.getX();

	}

	public Point2D intersectionPoint(Line2D line2) {

		// y1 = m1x +n1
		// y2 = m2x +n2
		// m1x + n1 = m2x + n2
		// (m1 - m1) * x = n2 - n1
		// x = n2 - n1 / m1 - m2

		// Geraden parallel
		if (this.m == line2.getM()) {
			return null;
		}

		double xIntersectionValue = (line2.getN() - this.n)
				/ (this.m - line2.getM());
		double yIntersectionValue = yForX(xIntersectionValue);

		return new Point2D.Double(xIntersectionValue, yIntersectionValue);

	}

	// y = mx + n
	// y - n = mx
	// x = (y - n ) / m
	public double xForY(double y) {
		return (y - n) / m;
	}

	public double yForX(double x) {
		return m * x + n;
	}

	public double getM() {
		return m;
	}

	public double getN() {
		return n;
	}

	@Override
	public String toString() {
		return "x1: " + this.getX1() + ", y1: " + this.getY1() + ", x2: "
				+ this.getX2() + ", y2: " + this.getY2() + ", m: " + m + ", "
				+ "n: " + n;
	}

}
